package cn.bugstack.trigger.job;

import cn.bugstack.domain.task.model.entity.TaskEntity;
import cn.bugstack.domain.task.service.ITaskService;
import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 19872
 * mq消息补偿机制
 */
@Slf4j
@Component()
public class SendMessageTaskJob {
    @Resource
    private ITaskService taskService;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private IDBRouterStrategy dbRouter;

    @Scheduled(cron = "0/5 * * * * *")
    public void exec(){
        try {
           // 获取分库数量
            int dbCount = dbRouter.dbCount();
            // 逐个扫码库表
            for (int i = 1; i <= dbCount; i++) {
                int finalDbIdx = i;
                threadPoolExecutor.execute(() -> {
                    try {
                        dbRouter.setDBKey(finalDbIdx);
                        dbRouter.setTBKey(0);
                        List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
                        if (taskEntities.isEmpty()) {
                            return;
                        }
                        // 发送MQ消息
                        for (TaskEntity taskEntity : taskEntities) {
                            // 开启线程发送，提高效率
                            threadPoolExecutor.execute(() -> {
                                try {
                                    taskService.sendMessage(taskEntity);
                                    taskService.updateTaskSendMessageCompleted(taskEntity.getMessageId(),taskEntity.getMessage());
                                    log.info("定时任务，发送MQ消息成功 userId：{} topic：{}",taskEntity.getUserId(),taskEntity.getTopic());
                                }catch (Exception e){
                                    log.error("定时任务，发送MQ消息失败 userId：{} topic：{}",taskEntity.getUserId(),taskEntity.getTopic());
                                    taskService.updateTaskSendMessageFail(taskEntity.getMessageId(),taskEntity.getMessage());
                                }
                            });
                        }
                    }finally {
                        dbRouter.clear();
                    }
                });
            }

        }catch (Exception e){
            log.error("定时任务，扫描MQ任务表发送消息失败。",e);
        }
    }

}
